import argparse

parser=argparse.ArgumentParser()
parser.add_argument("-i","--initial",type=int,default=7)
parser.add_argument("-e","--end",type=int,default=2000)
parser.add_argument("-p","--prefix",type=str,default="james")
parser.add_argument("-x","--suffix",type=str,default="deutschland")

parser.add_argument("-s","--save",type=str,default="saved")
parser.add_argument("-g","--generate",action="store_true")
parser.add_argument("-o","--overwrite",action="store_true")
parser.add_argument("-l","--load",type=str,default="saved")

args=parser.parse_args()

import rstr
import random
import os

import subprocess

def execute(command):
    program=subprocess.Popen(command,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    stdout,stderr=program.communicate()
    #print(stdout,stderr)
    return stdout, stderr

def check_password(user):
    #user = "james{}deutschland".format(user_index)
    stdout, stderr = execute(["bash","-c","cat ~/.git-credentials"])
#    print(stdout)
    stdout = stdout.decode("utf-8").split("\n")
#    print(stdout)
    stdout = [x for x in stdout if user in x]
    length = len(stdout)
    if length >1:
        print("warning: duplication found for",user)
    elif length == 1:
        print("credential found for",user)
    else:
        print("good. will insert right away.")
    return length == 0
#    print(stdout)
#    candidate = stdout[0]
#    return candidate

array=None
def pwd():
    core=r"[a-zA-Z0-9_]{4,5}[0-9]{3,4}[a-zA-Z]{2,3}"
    start=rstr.xeger(core)
    target=random.randint(0,len(start))
    stringlist=[x for x in start]
    stringlist.insert(target, random.choice([".","_","-"]))
    password="".join(stringlist)
#    print(password)
    return password

def get_name(name):
    return name+".confidential"
def save_array(array):
    assert type(array) == list
    assert type(array[0]) == str
    with open(get_name(args.save),"w+") as f:
        f.write("\n".join(array))
def pretty_print(array):
    return [x.replace(" ","\n") for x in array]
def load_array():
    with open(get_name(args.load),"r") as f:
        return pretty_print(f.read().split("\n"))
def load_saved_array():
    with open(get_name(args.save),"r") as f:
        return pretty_print(f.read().split("\n"))
def work_loop(array):
    length=len(array)
    print("total",length,"records generated.")
    cursor=0
    print("record #{}:".format(cursor))
    print(array[cursor])
    def copy_password():
        cred_list = array[cursor].split("\n")
        password = cred_list[1]
        tmpfile = ".confidential"
        with open(tmpfile,"w+") as f:
            f.write(password)
        os.system("bash -c \"cat {} | termux-clipboard-set\"".format(tmpfile))
        os.remove(tmpfile)
        print("copied password for user",cred_list[0])
    copy_password()
    while True:
        cmd = input("j<number> to jump to given index, a to add item to ~/.git-credentials, f to move forward, b to move backward, e to exit.\n")
        if len(cmd)== 1:
            if cmd == "a":
                print("will add item",cursor)
                cred_list = array[cursor].split("\n")
                if check_password(cred_list[0]):
                    os.system("bash -c \"echo https://{}:{}@github.com >> ~/.git-credentials\"".format(*cred_list))
            elif cmd == "f":
                if length > cursor+2:
                    cursor+=1
                else:
                    print("at the end of array!")
                    continue
            elif cmd == "b":
                if cursor > 0:
                    cursor -=1
                else:
                    print("at the beginnint of the array!")
                    continue
            elif cmd == "e":
                print("program will exit.")
                break
            else:
                print("command \"{}\" does not exist.".format(cmd))
                continue
        elif len(cmd)>1:
            if cmd[0]=="j":
                source=cmd[1:]
                try:
                    number=int(source)
                    if number >=0 and number < length:
                        cursor=number
                        print("jumped to item",cursor)
                    else:
                        print("number",number,"not in range [{},{}]".format(0,length))
                        continue
                except:
                    print("cannot parse \"{}\" as integer".format(source))
                    continue
            else:
                print("command \"{}\" does not exist.".format(cmd))
                continue
        else:
            print("command \"{}\" does not exist.".format(cmd))
            continue
        print("record #{}:".format(cursor))
        print(array[cursor])
        copy_password()

if args.generate:
    try:
        array=load_saved_array()
        print("array exists!")
    except:
        print("previous generated array not found")
        pass
    if ( not args.overwrite ) and ( array is not None) :
        print("will use previously generated array")
    else:
        print("will generate things.")
        init, end = args.initial, args.end
        assert init <= end
        assert init > 0
        prefix, suffix = args.prefix, args.suffix
        generator = ("".join([prefix, str(x), suffix])+" "+pwd() for x in range(init,end+1))
        save_array(list(generator))
        array=load_saved_array()
else:
    print("will load records.")
    array=load_array()
work_loop(array)
